/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.controller.pf;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.StringUtil;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.pf.BaseBusinessIndicatorsNew;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.pf.IBaseBusinessIndicatorsRqNewService;
import com.plian.system.service.pf.IBaseIndicatorsRqChangeNewService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pf.BaseBusinessIndicatorsNewVO;
import com.plian.system.wrapper.pf.BaseBusinessIndicatorsNewWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 任期经营业绩考核指标主表 控制器
 *
 * @author zhangsk
 * @since 2025-01-16
 */
@RestController
@AllArgsConstructor
@RequestMapping("api/basebusinessindicatorsRqNew")
@Api(value = "BaseBusinessIndicatorsRqController", tags = "任期经营业绩考核指标主表 控制器")
public class BaseBusinessIndicatorsRqNewController extends BaseController {

	private IBaseIndicatorsRqChangeNewService baseIndicatorsRqChangeService;

	private IBaseBusinessIndicatorsRqNewService baseBusinessIndicatorsRqService;

	private FormWorkflowService formWorkflowService;

	private BaseBusinessIndicatorsNewWrapper baseBusinessIndicatorsWrapper;

	private GzwProperties gzwProperties;
	/**
	 * 详情
	 */
	@PostMapping("/detail")
	@ApiOperation(value = "详情", notes = "传入baseBusinessIndicators")
	public R<BaseBusinessIndicatorsNewVO> detail(@RequestBody BaseBusinessIndicatorsNew baseBusinessIndicators) {
		baseBusinessIndicators.setModuleType(1);
		BaseBusinessIndicatorsNew detail = baseBusinessIndicatorsRqService.getOne(Condition.getQueryWrapper(baseBusinessIndicators));
		BaseBusinessIndicatorsNewVO baseBusinessIndicatorsVO = baseBusinessIndicatorsWrapper.entityToVO(detail);
		R<BaseBusinessIndicatorsNewVO> detailObj = baseBusinessIndicatorsRqService.getDetailObj(baseBusinessIndicatorsVO);
		BaseBusinessIndicatorsNewVO indicatorsVO = detailObj.getPageData();
		if (baseBusinessIndicatorsVO.getFormType().equals(FormTypeConstant.PF_BASE_BUSINESS_INDICATORS_CHANGE_RQ + "")){
			//变更详情，加上上个版本的详情
			BaseBusinessIndicatorsNewVO lastVO = baseBusinessIndicatorsRqService.getDetailObj(baseBusinessIndicatorsWrapper.entityToVO(baseIndicatorsRqChangeService.getById(detail.getLastVersionId()))).getPageData();
			baseBusinessIndicatorsVO.setLastInfoVO(lastVO);
		}
		return R.data(indicatorsVO);
	}

	/**
	 * 分页
	 */
	@PostMapping("/list")
	@ApiOperation(value = "分页", notes = "传入query")
	public ListResult<BaseBusinessIndicatorsNewVO> list(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		if (query.getAscs()==null&&query.getDescs()==null){
			query.setDescs("create_time");
		}
		QueryWrapper<BaseBusinessIndicatorsNew> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new BaseBusinessIndicatorsNew()), entityList
		);
		TokenSearch<BaseBusinessIndicatorsNew> tokenSearch = new TokenSearch<>();
		queryWrapper.eq("module_type",1);
		tokenSearch.addTokenQuery(queryWrapper, query);
		IPage<BaseBusinessIndicatorsNew> pages = baseBusinessIndicatorsRqService.page(Condition.getPage(query), queryWrapper);
		List<BaseBusinessIndicatorsNewVO> baseBusinessIndicatorsVOS = baseBusinessIndicatorsWrapper.entityToVO(pages.getRecords());
		ListResult<BaseBusinessIndicatorsNewVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(baseBusinessIndicatorsVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@Resubmit(delaySeconds = 0)
	@ApiOperation(value = "新增或修改", notes = "传入appraisalIndex")
	@LogOperation("任期经营业绩考核指标-提交")
	public R<BaseBusinessIndicatorsNew> submit(@Valid @RequestBody BaseBusinessIndicatorsNew baseBusinessIndicators) {
		if(baseBusinessIndicators!=null){
			baseBusinessIndicators.setModuleType(1);
		}
		if (!Optional.ofNullable(baseBusinessIndicators.getId()).isPresent()){
			String checkMessage = baseBusinessIndicatorsRqService.checkYear(baseBusinessIndicators);
			if (StringUtil.isNotBlank(checkMessage)){
				return new R(CustomCode.builder().message(checkMessage).code(1999).success(false).build());
			}
		}


		boolean result = baseBusinessIndicatorsRqService.submit(baseBusinessIndicators);
		HashMap<String, Object> processVariable = new HashMap<>();
		formWorkflowService.startProcessAndSimulate(String.valueOf(baseBusinessIndicators.getId()),baseBusinessIndicators.getFormType(),processVariable);

		return result ? R.data(baseBusinessIndicators) : new R(CommonCode.FAIL);
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperation(value = "删除", notes = "传入 ids")
	@LogOperation("任期经营业绩考核指标-删除")
	public R remove(@RequestBody PageData pd) {
		boolean r = true;
		List<String> ids = (List<String>)pd.get("ids");
		for (String id :ids){
			if (r){
				BaseBusinessIndicatorsNew businessIndicators = baseBusinessIndicatorsRqService.getById(id);
				if (businessIndicators.getFormType().equals(String.valueOf(FormTypeConstant.PF_BASE_BUSINESS_INDICATORS_RQ))){
					//初始删除
					r = baseBusinessIndicatorsRqService.deleteLogic(Collections.singletonList(businessIndicators.getId()));
				}else if (businessIndicators.getFormType().equals(String.valueOf(FormTypeConstant.PF_BASE_BUSINESS_INDICATORS_CHANGE_RQ))){
					//变更删除
					r = baseIndicatorsRqChangeService.deleteLogic(Collections.singletonList(businessIndicators.getId()));
				}
			}else {
				return new R(CommonCode.FAIL);
			}
		}

		return new R(CommonCode.SUCCESS) ;
	}

	@PostMapping("/submit-change")
	@Resubmit(delaySeconds = 0)
	@ApiOperation(value = "新增或修改-变更信息", notes = "传入baseBusinessIndicators")
	@LogOperation("任期经营业绩考核指标-变更")
	public R<BaseBusinessIndicatorsNew> submitChange(@Valid @RequestBody BaseBusinessIndicatorsNew baseBusinessIndicators) {
		if(baseBusinessIndicators!=null){
			baseBusinessIndicators.setModuleType(1);
		}
		boolean result = baseIndicatorsRqChangeService.submit(baseBusinessIndicators);

		return result ? R.data(baseBusinessIndicators) : new R(CommonCode.FAIL);
	}

	@PostMapping("/version-list")
	@ApiOperation(value = "查看版本", notes = "传入 initialId")
	public ListResult<BaseBusinessIndicatorsNewVO> versionList(@RequestBody Query query) {
		return baseBusinessIndicatorsRqService.versionList(query);
	}
}
